package com.jumi.microservice.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jumi.microservice.constant.ExceptionEnum;
import com.jumi.microservice.constant.TemplateSwitchEnum;
import com.jumi.microservice.domain.*;
import com.jumi.microservice.dto.reponse.JmJpushUserResponse;
import com.jumi.microservice.mapper.MessageMailMapper;
import com.jumi.microservice.mapper.MessagePushLogMapper;
import com.jumi.microservice.mapper.MessageTemplateMapper;
import com.jumi.microservice.rocketmq.MessageMqListener;
import com.jumi.microservice.service.IMessageService;
import com.jumi.microservice.service.JmJpushUserService;
import com.jumi.microservice.service.MessageService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@DubboService
@Transactional
public class IMessageServiceImpl implements IMessageService {
    private static final Logger log = LoggerFactory.getLogger(MessageMqListener.class);
    @Resource
    private MessageTemplateMapper messageTemplateMapper;

    @Resource
    private MessagePushLogMapper messagePushLogMapper;

    @Resource
    private MessageService messageService;

    @DubboReference
    private JmJpushUserService jmJpushUserService;

    @Resource
    private MessageMailMapper messageMailMapper;

    @Override
    public Boolean messageSend(MessageBody body) {
        //查询消息模板信息
        MessageTemplate template = messageTemplateMapper.selectById(body.getTemplateId());
        //执行发送
        MessagePushLog pushLog = doSend(body, template);
        //消息推送日志表
        addLog(pushLog);
        return Boolean.TRUE;
    }

    @Override
    public Boolean messageAllSend(AppMessageAll appMessageAll) {
        return messageService.messageSend(appMessageAll);
    }

    @Override
    public Boolean messageSmsSend(MessageSmsQuery messageSmsQuery) {
        MessageSms sms = new MessageSms();
        //接收人手机号
        sms.setSmtPhone(messageSmsQuery.getSMSMessage().getReceiverMobilePhone());
        //短信模版id
        sms.setSmtShortId(messageSmsQuery.getSMSMessage().getSmtShortId());
        //短信内容
        sms.setSmtContent(messageSmsQuery.getSMSMessage().getMessageContent());
        //短信替换内容
        sms.setSmtParameter(JSONObject.toJSONString(messageSmsQuery.getSMSMessage().getMessageParams()));
        //0:设备统一发送,1:短信单独发送
        sms.setSmtType(1);
        Long logId = messageService.messageSend(sms);
        if(logId > 0L){
            return Boolean.TRUE;
        }else{
            return Boolean.FALSE;
        }
    }


    private MessagePushLog doSend(MessageBody query, MessageTemplate template) {
        //获取用户信息
        List<JmJpushUserResponse> jgPushByUid = jmJpushUserService.getJgPushByUid(query.getReceiverMemberId().intValue());
        //站内信
        Long mailId = 0L;
        //app通知
        Long appId = 0L;
        //短信
        Long smsId = 0L;
        //微信公众号
        Long weixinId = 0L;
        //微信小程序
        Long appletsId = 0L;
        //返回消息
        String message = "";

        //拼接跳转地址所需参数
        Map<String,String> push = query.getLink();
        push.put("type",query.getTemplateId().toString());
        query.setLink(push);
        if(query.getReceiverMemberId() != null){
            //发送站内信
            mailId = send4Station(query, template);
        }else{
            message += "未获取到接收人id";
        }
        if(jgPushByUid != null){
            //遍历用户手机号和设备号
            JmJpushUserResponse jmJpushUserResponse = new JmJpushUserResponse();
            jmJpushUserResponse.setMobile(jgPushByUid.get(0).getMobile());
            jmJpushUserResponse.setRegisterId(jgPushByUid.stream().map(jm->{return jm.getRegisterId().toString();}).collect(Collectors.joining(",")));
            //设备号不等于null
            if(jmJpushUserResponse.getRegisterId() != null){
                //存入站内信id
                Map<String,String> push2 = query.getLink();
                if(mailId==0L){
                    push2.put("messageId","");
                }else{
                    push2.put("messageId",mailId.toString());
                }
                query.setLink(push2);
                //发送app通知
                appId = send4App(query, template, jmJpushUserResponse);
            }else{
                message += "未获取到用户设备号";
            }
            //手机号不等于null
            if(jmJpushUserResponse.getMobile() != null){
                //发送短信
                smsId = send4SMS(query, template, jmJpushUserResponse);
            }else{
                message += "未获取到用户手机号";
            }
        }else{
            message += "未获取到用户信息";
        }

        //微信公众号
        weixinId = send4WeChat(query, template);
        //微信小程序
        appletsId = send4WeChatApplets(query, template);

        if(message==""){
            message = "success";
        }
        //插入推送记录日志
        MessagePushLog pushLog = new MessagePushLog();
        pushLog.setTemplateId(template.getId());
        pushLog.setMailId(mailId);
        pushLog.setAppId(appId);
        pushLog.setSmsId(smsId);
        pushLog.setWeixinId(weixinId);
        pushLog.setAppletsId(appletsId);
        pushLog.setMessage(message);
        return pushLog;
    }

    private void addLog(MessagePushLog pushLog) {
        messagePushLogMapper.insert(pushLog);
    }

    /**
     * 站内信默认开关，0关，1开
     * @param query
     * @param template
     */
    private Long send4Station(MessageBody query, MessageTemplate template) {
        if (TemplateSwitchEnum.OPEN == template.getSmtMessageSwitch()) {
            if(null == query.getMessageStation()){
                log.error(ExceptionEnum.FAIL_NULL_MAIL.getMessage());
                return 0L;
            }
            MessageMail mail = new MessageMail();
            //消息模板id
            mail.setTemplateId(template.getId());
            //1：交易物流通知,2：商品活动通知,3：系统消息通知,4：余额变动通知
            mail.setTemplateTitleType(template.getTitleType());
            //发送人
            mail.setSdMemberId(query.getSenderMemberId());
            //接收人
            mail.setReMemberId(query.getReceiverMemberId());
            //站内信内容
            mail.setMessageContent(query.getMessageStation().getMessageContent());
            //跳转地址所需参数
            mail.setLink(JSONObject.toJSONString(query.getLink()));
            //图片地址
            mail.setMessageImg(query.getMessageImg());

            return messageService.messageSend(mail);
        }
        return 0L;
    }

    /**
     * app通知开关，0关，1开
     * @param query
     * @param template
     */
    private Long send4App(MessageBody query, MessageTemplate template,JmJpushUserResponse jgPushByUid) {
        if (TemplateSwitchEnum.OPEN == template.getSmtAppSwitch()) {
            //判断app消息体是否为空
            if(null == query.getAppMessage()){
                log.error(ExceptionEnum.FAIL_NULL_APP.getMessage());
                return 0L;
            }
            //判断设备号是否为空
            if(jgPushByUid.getRegisterId().isEmpty()){
                log.error(ExceptionEnum.FAIL_NULL_APP.getMessage());
                return 0L;
            }

            MessageApp app = new MessageApp();
            //jPush设备id
            app.setAppRegisterid(jgPushByUid.getRegisterId());
            //模板名称
            app.setAppTitle(template.getSmtName());
            //app模板内容
            app.setAppContent(query.getAppMessage().getMessageContent());
            //获取站内信未读消息数量
            Integer unreadNum = messageMailMapper.selectCount(Wrappers.<MessageMail>lambdaQuery()
                    .eq(MessageMail::getReMemberId,query.getReceiverMemberId())
                    .eq(MessageMail::getMessageOpen,0)
                    .eq(MessageMail::getIsDel,0));

            return messageService.messageSend(app,query,unreadNum);
        }
        return 0L;
    }

    /**
     * 短信默认开关，0关，1开
     * @param query
     * @param template
     */
    private Long send4SMS(MessageBody query, MessageTemplate template,JmJpushUserResponse jgPushByUid) {
        if (TemplateSwitchEnum.OPEN == template.getSmtShortSwitch()) {
            //判断短信消息体是否为空
            if(null == query.getSmsMessage()){
                log.error(ExceptionEnum.FAIL_NULL_SMS.getMessage());
                return 0L;
            }
            //判断短信消息模板id是否为空
            if(template.getSmtShortId().isEmpty()){
                log.error(ExceptionEnum.FAIL_NULL_SMS.getMessage());
                return 0L;
            }
            //判断手机号是否为空
            if(jgPushByUid.getMobile().isEmpty()){
                log.error(ExceptionEnum.FAIL_NULL_SMS.getMessage());
                return 0L;
            }
            //判断短信推送参数是否为空
            if(query.getSmsMessage().getMessageParams().isEmpty()){
                log.error(ExceptionEnum.FAIL_NULL_SMS.getMessage());
                return 0L;
            }

            MessageSms sms = new MessageSms();
            //短信模版id
            sms.setSmtShortId(template.getSmtShortId());
            //接收人手机号
            sms.setSmtPhone(jgPushByUid.getMobile());
            //短信内容
            sms.setSmtContent(template.getSmtShortContent());
            //短信替换内容
            sms.setSmtParameter(JSONObject.toJSONString(query.getSmsMessage().getMessageParams()));

            return messageService.messageSend(sms);
        }
        return 0L;
    }

    /**
     * 微信公众号通知开关，0关，1开
     * @param query
     * @param template
     */
    private Long send4WeChat(MessageBody query, MessageTemplate template) {
        if (TemplateSwitchEnum.OPEN == template.getSmtWeixinSwitch()) {
            //TODO 微信公众号通知推送
        }
        return 0L;
    }

    /**
     * 小程序通知开关，0关，1开
     * @param query
     * @param template
     */
    private Long send4WeChatApplets(MessageBody query, MessageTemplate template) {
        if (TemplateSwitchEnum.OPEN == template.getSmtAppletsSwitch()) {
            //TODO 小程序通知推送
        }
        return 0L;
    }

    @Override
    public List<MessageTemplate> messageTemplateList() {
        LambdaQueryWrapper<MessageTemplate> goodsWrapper = Wrappers.lambdaQuery();
        goodsWrapper.eq(MessageTemplate::getIsDel, 0);
        goodsWrapper.orderByDesc(MessageTemplate::getId);
        List<MessageTemplate> messageTemplates = messageTemplateMapper.selectList(goodsWrapper);
        return messageTemplates;
    }

    @Override
    public MessageTemplate messageTemplateOne(Long id) {
        MessageTemplate messageTemplate = messageTemplateMapper.selectById(id);
        return messageTemplate;
    }
}
